//
//  M4UserBankViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit
import KakaJSON

class M4UserBankViewController: M4BaseViewController {
    
    lazy var M4NullView: M4DataNullView = {
        let nullV = UINib(nibName: "M4DataNullView", bundle: nil).instantiate(withOwner: self).last as! M4DataNullView
        nullV.M4NullUpdateUI(describe: "No ha agregado una tarjeta bancaria todavía", buttonTitle: "Agregar tarjeta bancaria")
        nullV.M4NullButtonBlock = {
            self.M4ToAddBankInfo()
        }
        return nullV
    }()
    
    @IBOutlet weak var M4BankListAddButton: UIButton!
    
    @IBOutlet weak var M4BankListAddHeight: NSLayoutConstraint!
    
    private var M4BankListData: [M4BankListModel] = []
    
    private var M4BankTotal: Int = 3
    
    var fromDetail: Bool = false
    
    var M4SelectBankBlock: ((M4BankListModel?) -> Void)?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4UserBankListNet()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Tarjeta bancaria", M4NavTitleColor: COLOR_333333)
        self.M4BankListAddButton.isHidden = true
        self.M4BankListAddHeight.constant = 0
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight())
            make.left.right.equalToSuperview()
            make.bottom.equalTo(M4BankListAddButton.snp.top)
        }
        M4addRefreshToTaleView { [weak self] in
            self?.M4UserBankListNet()
        }
    }
    
    @IBAction func M4BankListAddClick(_ sender: UIButton) {
        M4ToAddBankInfo()
        sender.M4EventUnavailable = false
    }
    
    private func M4ToAddBankInfo() {
        /*首次添加银行卡不需要OTP验证*/
        if self.M4BankListData.count == 0 {
            let page = M4FourInfoViewController()
            page.isInfoPage = false
            self.navigationController?.pushViewController(page, animated: true)
        } else {
            let page = M4BankVerficationViewController()
            self.navigationController?.pushViewController(page, animated: true)
        }
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        if action.M4ActionType == 0 && fromDetail {
            let model = action.M4ActionData as? M4BankListModel
            M4SelectBankBlock?(model)
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    override func M4DataRefresh() {
        M4UserBankListNet()
    }

}

extension M4UserBankViewController {
    
    private func M4BankListDataSource() {
        M4TableSources.removeAll()
        M4BankListData.forEach { bank in
            M4TableSources.append(M4TableViewCellData("M4BankCardCell", XIB: true, bank))
        }
        M4TableView.reloadData()
        M4TableView.backgroundView = M4BankListData.count <= 0 ? M4NullView : nil
    }
    
    private func M4UserBankListNet() {
        let para: [String : Any] = ["SAggUn": "ESP", "KyyIT": M4UserDataManager.m4UserShare.M4Itemcode, "ZBtxou": M4UserDataManager.m4UserShare.M4Token, "VrFBaKyyTeT": 5, "TPcYi": M4UserDataManager.m4UserShare.M4ProductCode]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4CreditedInfo, .post, params: para)) { model in
            self.M4endRefresh()
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let list = data?["RXdO"] as? [[String : Any]]
                self.M4BankListData = list?.kj.modelArray(M4BankListModel.self) ?? []
                self.M4BankTotal = data?["tLsnkxs"] as? Int ?? 0
                if self.M4BankListData.count != 0 && self.M4BankListData.count < self.M4BankTotal {
                    self.M4BankListAddButton.isHidden = false
                    self.M4BankListAddHeight.constant = 49
                }
                else {
                    self.M4BankListAddButton.isHidden = true
                    self.M4BankListAddHeight.constant = 0
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
            self.M4BankListDataSource()
        }
    }
    
}
